package com.thrd.basicframework.media;

import android.app.Service;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.text.TextUtils;

import androidx.annotation.Nullable;

import com.thrd.basicframework.LrcMusic;
import com.thrd.basicframework.utils.LogUtil;
import com.thrd.basicframework.utils.LrcUtils;
import com.thrd.basicframework.utils.ProxyCache;
import com.thrd.basicframework.utils.TimeUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;


/**
 * @author: ${唐杰}
 * @date: 2021/4/9
 */
public class MusicService extends Service {
    private static final String TAG = "MusicService";
    private MediaPlayer mediaPlayer;
    //是否播放
    private boolean isPlay=false;
    private Thread mLyricsRunnable;
    private boolean isExit=false;
    private List<LrcMusic> musicList;
    private Runnable runnable=new Runnable() {
        @Override
        public void run() {
            while (true){
                if(!isPlay){
                    try {
                        LogUtil.e(TAG,"线程休眠");
                        Thread.sleep(Integer.MAX_VALUE);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
              //  LogUtil.e(TAG,"线程运行中");
                whileLyrics();
                setSwitchThremeTime();

                if(isExit){
                    return;
                }
            }
        }
    };

    public class MusicBinder extends Binder {

        public MusicService getService(){
            return MusicService.this;
        }
    }

    //通过binder实现调用者client与Service之间的通信
    private MusicBinder binder = new MusicBinder();


    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return binder;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        if(mLyricsRunnable==null){
            mLyricsRunnable=new Thread(runnable);
            mLyricsRunnable.start();
        }

        mediaPlayer = new MediaPlayer();
        mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                if(isPlay){
                    play();
                }
                if(onMusicClick!=null){
                    onMusicClick.onPrepared(mp);
                }
            }
        });

        mediaPlayer.setOnInfoListener(new MediaPlayer.OnInfoListener() {
            @Override
            public boolean onInfo(MediaPlayer mp, int what, int extra) {
                return false;
            }
        });

        mediaPlayer.setOnBufferingUpdateListener(new MediaPlayer.OnBufferingUpdateListener() {
            @Override
            public void onBufferingUpdate(MediaPlayer mp, int percent) {
                LogUtil.e(TAG,"length="+percent);
            }
        });
        //  mediaPlayer.setOnPreparedListener();

    }

    private String path;
    public void setDataSource(String path){
        if(TextUtils.isEmpty(path))return;
        this.path= ProxyCache.getInstance().getProxy().getProxyUrl(path);
        LogUtil.e(TAG,"length="+ProxyCache.getInstance().getProxy().getLength(path));
        if(musicList!=null){
            musicList.clear();
            musicList=null;
        }
        try {
            if(mediaPlayer!=null){
                mediaPlayer.reset();
                mediaPlayer.setDataSource(path);
                mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                mediaPlayer.prepareAsync();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }



    /**
     * 获取歌词信息
     * @param path
     */
    public void setDataLyrics(String path){


        if (onMusicClick != null) {
            onMusicClick.onClickLrc(new LrcMusic(0, "歌词加载中..."), 0);
            onMusicClick.onClickLrcDownload(path, new LrcDownloadListener() {
                @Override
                public void onSuccess(File file) {
                    try {
                        musicList = LrcUtils.redLrc(new FileInputStream(file));
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                        onMusicClick.onClickLrc(new LrcMusic(0, "歌词加载失败..."), 0);
                    }
                    // onMusicClick.onClickLrc(new LrcMusic(0,"歌词加载中..."),0);
                }

                @Override
                public void onFailure(int code, String s) {
                    onMusicClick.onClickLrc(new LrcMusic(0, "歌词加载失败..."), 0);
                }
            });
        }
        //  musicList= LrcUtils.redLrc(new FileInputStream(path));
        // musicList= LrcUtils.redLrc(getAssets().open("yyp.lrc"));

    }




    //返回当前的播放进度，是double类型，即播放的百分比
    public double getProgress(){
        int position = mediaPlayer.getCurrentPosition();

        int time = mediaPlayer.getDuration();

        double progress = (double)position / (double)time;

        return progress;
    }

    //通过activity调节播放进度
    public void setProgress(int max , int dest){
        int time = mediaPlayer.getDuration();
        mediaPlayer.seekTo(time*dest/max);
    }


    public void seekTo(int dest){
        if(mediaPlayer!=null)
            mediaPlayer.seekTo(dest);
        mLyricsRunnable.interrupt();
    }

    //測试播放音乐
    public void play(){
        isPlay=true;
        if(mediaPlayer != null){
            mediaPlayer.start();
        }
        mLyricsRunnable.interrupt();

    }
    //暂停音乐
    public void pause() {
        isPlay=false;
        if (mediaPlayer != null && mediaPlayer.isPlaying()) {
            mediaPlayer.pause();
        }

    }

    //service 销毁时。停止播放音乐，释放资源
    @Override
    public void onDestroy() {
        isPlay=false;
        isExit=true;
        if(mLyricsRunnable!=null){
            mLyricsRunnable.stop();
        }
        // 在activity结束的时候回收资源
        if (mediaPlayer != null && mediaPlayer.isPlaying()) {
            mediaPlayer.stop();
            mediaPlayer.release();
            mediaPlayer = null;
        }

        super.onDestroy();
    }

    // 主线程
    private   Handler handler = new Handler(Looper.getMainLooper());

    /**
     * 切换到主线程线程
     * @param lrcMusic
     * @param position
     */
    private void setSwitchThreme(final LrcMusic lrcMusic, final int position){
        if(handler!=null&&onMusicClick!=null){
            handler.post(new Runnable() {
                @Override
                public void run() {
                    onMusicClick.onClickLrc(lrcMusic,position);
                }
            });
        }
    }

    /**
     * 切换到主线程线程
     */
    private void setSwitchThremeTime(){
        if(handler!=null&&onMusicClick!=null&&mediaPlayer!=null){
            final int position=mediaPlayer.getCurrentPosition();
            final String time=TimeUtils.getDateToString(position,"mm:ss");
            handler.post(new Runnable() {
                @Override
                public void run() {
                    onMusicClick.onClickProgress(position,time);
                }
            });
        }
    }


    private LrcMusic lrcMusic;
    //必须子线程运行
    private void whileLyrics(){

        if(musicList!=null&&musicList.size()>0){
            //  LogUtil.e(TAG,"歌词不为空");
            int current=  mediaPlayer.getCurrentPosition();
            //LogUtil.e(TAG,"播放器时间="+current);
            int  position = LrcUtils.binarysearch(musicList,current);
            if(position<0)return;
            LrcMusic  mLrcMusic=musicList.get(position);
            if((lrcMusic==null&&mLrcMusic!=null)||(mLrcMusic!=null&&lrcMusic.hashCode()!=mLrcMusic.hashCode())){
                // LogUtil.e(TAG,"查找到了数据");
                lrcMusic=mLrcMusic;
                LogUtil.e(TAG,"歌词："+lrcMusic.getLrc()+"\n播放器时间="+mediaPlayer.getCurrentPosition()+"\n 歌曲时间="+lrcMusic.getTime());
                setSwitchThreme(lrcMusic,position);

            }

        }
    }



    private OnMusicClick onMusicClick;

    public OnMusicClick getOnMusicClick() {
        return onMusicClick;
    }

    public void setOnMusicClick(OnMusicClick onMusicClick) {
        this.onMusicClick = onMusicClick;
    }
}
